package com.example.musicplayer.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.musicplayer.activity.BaseActivity;
import com.example.musicplayer.dialogTools.LyricSizeSetDialog;
import com.example.musicplayer.fragment.dialogFragment.LyricFeaturesDialogFragment;
import com.example.musicplayer.musicTools.Lyric;
import com.example.musicplayer.R;
import com.example.musicplayer.adapter.MusicLyricAdapter;
import com.example.musicplayer.service.MusicService;

public class MusicPlayTab3Fragment extends BaseFragment implements View.OnClickListener {
    private TextView mTextViewTitle;
    private TextView mTextViewArtist;
    private ImageView mImageViewPlay;
    private ListView mListView;
    private boolean mScrollStateIdle = true;
    private Tab3CallBackListener mTab3CallBackListener;
    private MusicService.MusicBinder mMusicBinder;
    private MusicLyricAdapter mAdapter;

    private final Runnable mScrollLyric = new Runnable() {
        @Override
        public void run() {
            if (mMusicBinder != null && mMusicBinder.isPlaying()) {
                int position = mAdapter == null ? 0 : mAdapter.getNowPosition();
                scrollTo(position, 100);
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_music_play_tab3, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        addListener();
        setEnableTimer(true, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (mTab3CallBackListener != null) {
            mMusicBinder = mTab3CallBackListener.getMusicBinder();
        }
        initListView();
    }

    @Override
    public void onStart() {
        super.onStart();
        updateView();
    }

    @Override
    public void onStop() {
        super.onStop();
        pauseTimer();
    }

    @Override
    protected boolean onRefreshView() {
        if (mMusicBinder != null) {
            int nowPosition = mAdapter.getNowPosition();
            int targetPosition;
            if (mMusicBinder.getCurrent() >= Lyric.getStartTime(nowPosition)) {
                targetPosition = nowPosition;
            } else {
                targetPosition = 0;
            }
            for (; targetPosition < Lyric.getSize(); targetPosition++) {
                if (mMusicBinder.getCurrent() >= Lyric.getStartTime(targetPosition) &&
                        mMusicBinder.getCurrent() < Lyric.getStartTime(targetPosition + 1)) {
                    break;
                }
            }
            if (targetPosition != nowPosition) {
                mAdapter.setNowPosition(targetPosition);
                mAdapter.notifyDataSetChanged();
                if (mTab3CallBackListener != null) {
                    mTab3CallBackListener.musicLyricChanged(Lyric.getLyric(mAdapter.getNowPosition()));
                }
                if (mScrollStateIdle) {
                    scrollTo(targetPosition, 500);
                }
            }
        }
        return true;
    }

    private void initView() {
        if (getView() != null) {
            mTextViewTitle = getView().findViewById(R.id.textview_music_play_tab3_title);
            mTextViewArtist = getView().findViewById(R.id.textview_music_play_tab3_artist);
            mImageViewPlay = getView().findViewById(R.id.imageview_music_play_tab3_play);
            mListView = getView().findViewById(R.id.listview_music_play_tab3_lyric);
        }
    }

    private void addListener() {
        if (getView() != null) {
            getView().findViewById(R.id.imageview_music_play_tab3_comment).setOnClickListener(this);
            getView().findViewById(R.id.imageview_music_play_tab3_lyric).setOnClickListener(this);
            mImageViewPlay.setOnClickListener(this);
            mTextViewTitle.setOnClickListener(this);
        }
    }

    //更新fragment的显示内容
    private void updateView() {
        if (mMusicBinder != null) {
            changeMusicState(mMusicBinder.isPlaying());
            mTextViewTitle.setText(mMusicBinder.getTitle());
            mTextViewArtist.setText(mMusicBinder.getArtist());
        } else {
            changeMusicState(false);
        }
    }

    private void initListView() {
        //读进去当前歌词文件并初始化
        if (mMusicBinder != null) {
            if (mMusicBinder.getId() != Lyric.getCurrentMusicId()) {
                Lyric.create(mMusicBinder.getLyricPath(), getResources(), mMusicBinder.getId());
            }
            mAdapter = new MusicLyricAdapter(getActivity(), 0);
            mListView.setAdapter(mAdapter);
            if (mTab3CallBackListener != null) {
                mTab3CallBackListener.musicLyricChanged(Lyric.getLyric(0));
            }
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    mAdapter.setNowPosition(position);
                    mMusicBinder.seekTo(Lyric.getStartTime(position));
                    scrollTo(position, 500);
                    mAdapter.notifyDataSetChanged();
                    if (mTab3CallBackListener != null) {
                        mTab3CallBackListener.musicLyricChanged(Lyric.getLyric(position));
                    }
                }
            });
            mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    mScrollStateIdle = (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE);
                    if (mScrollStateIdle) {
                        postDelayed(mScrollLyric, 3000);
                    } else {
                        removeCallbacks(mScrollLyric);
                    }
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                }
            });
        }
    }

    private void scrollTo(int position, int time) {
        if (isStarted()) {
            mListView.smoothScrollToPositionFromTop(position, getResources().getInteger(R.integer.offset_lyric), time);
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageview_music_play_tab3_comment:
                doClickComment();
                break;
            case R.id.imageview_music_play_tab3_lyric:
                doClickLyric();
                break;
            case R.id.imageview_music_play_tab3_play:
                doClickPlay();
                break;
            case R.id.textview_music_play_tab3_title:
                if (getActivity() instanceof BaseActivity) {
                    ((BaseActivity) getActivity()).jumpToMusicDetailsActivity();
                }
                break;
            default:
                break;
        }
    }

    private void doClickComment() {

    }

    //点击弹出歌词功能选择对话框
    private void doClickLyric() {
        //歌词功能选择对话框
        LyricFeaturesDialogFragment lyricDialog = new LyricFeaturesDialogFragment();
        lyricDialog.setLyricFeaturesListener(new LyricFeaturesDialogFragment.LyricFeaturesListener() {
            @Override
            public void changeChinese() {
                Lyric.changeChinese();
                mAdapter.notifyDataSetChanged();
                if (mTab3CallBackListener != null) {
                    mTab3CallBackListener.musicLyricChanged(Lyric.getLyric(mAdapter.getNowPosition()));
                }
            }

            @Override
            public void showLyricSizeSetDialog() {
                LyricSizeSetDialog setDialog = new LyricSizeSetDialog(MusicPlayTab3Fragment.this.getActivity());
                setDialog.setOnLyricSizeChangeListener(new LyricSizeSetDialog.LyricSizeChangeListener() {
                    @Override
                    public void onLyricSizeChange() {
                        mAdapter.notifyDataSetChanged();
                    }
                });
                setDialog.show();
            }
        });
        if (getActivity() != null) {
            lyricDialog.show(getActivity().getSupportFragmentManager(), "lyricFeaturesDialog");
        }
    }

    //处理播放和暂停事件
    private void doClickPlay() {
        if (mMusicBinder != null) {
            mMusicBinder.changePlayingState();
        }
    }

    //服务通知音乐播放状态改变时被调用
    public void changeMusicState(boolean state) {
        if (state) {
            mImageViewPlay.setImageDrawable(getResources().getDrawable(R.drawable.activity_music_play_tab3_start));
            if (isStarted()) {
                post(mScrollLyric);
                startTimer();
            }
        } else {
            mImageViewPlay.setImageDrawable(getResources().getDrawable(R.drawable.activity_music_play_tab3_pause));
            pauseTimer();
        }
    }

    //音乐准备后更新歌词界面
    public void updateMusicPrepared() {
        updateView();
        initListView();
    }

    public void setTab3CallBackListener(Tab3CallBackListener callBack) {
        mTab3CallBackListener = callBack;
    }

    //声明回调接口
    public interface Tab3CallBackListener {
        public MusicService.MusicBinder getMusicBinder();

        //音乐歌词改变时调用
        public void musicLyricChanged(String lyric);
    }
}